#coding=utf-8
'''
 一 编写with操作类Fileinfo()，定义__enter__和__exit__方法。完成功能：

 1.1 在__enter__方法里打开Fileinfo(filename)，并且返回filename对应的内容。如果文件不存在等情况，需要捕获异常。

 1.2 在__enter__方法里记录文件打开的当前日期和文件名。并且把记录的信息保持为log.txt。内容格式："2014-4-5 xxx.txt"
'''
import os
import logging

class Fileinfo(object):
      def __init__(self,file_path):
           self.file_path = file_path
      def __enter__(self):
          self.file_path = self.file_path
          try:
              c = open(self.file_path,'r')
              contents = c.read()
              c.close()
              print contents
          except IOError as e:
              logging.basicConfig(filename='D:/demo/error2.log', filemode='w', level=logging.DEBUG)
              logging.debug(e)
              logging.info('So should this')
              logging.warning('And this, too')




      def __exit__(self, exc_type, exc_val, exc_tb):
          logging.basicConfig(level=logging.DEBUG,filename='D:/demo/log.txt',format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S',filemode="w")
          logging.debug('This is debug message')
          logging.info('This is info message')
          logging.warning('This is warning message')


with Fileinfo('D:\demo127.txt') as s:
    pass

